package com.qwc.blog.web;

import com.qwc.blog.common.constant.ResponseConstant;
import com.qwc.blog.common.exception.AuthenticationException;
import com.qwc.blog.entity.vo.ApiError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;

/**
 * @author qiuwencong
 * @Date 2022/1/28
 * @Package com.qwc.blog.web
 * @Description
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 未知错误处理
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<ApiError> handleException(Throwable e){
        log.error(getStackTrace(e));
        return buildResponseEntity(ApiError.error(HttpStatus.BAD_REQUEST.value(),e.getMessage()));
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity<ApiError> duplicateKeyException(Exception e){
        log.error(getStackTrace(e));
        return buildResponseEntity(ApiError.error(HttpStatus.BAD_REQUEST.value(), ResponseConstant.DATA_EXISTED));
    }

    /**
     * 认证错误
     * @param e
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<ApiError> authenticationException(AuthenticationException e){
        log.error(getStackTrace(e));
        return buildResponseEntity(ApiError.error(HttpStatus.UNAUTHORIZED.value(),e.getMessage()));
    }

    /**
     * 处理所有接口数据验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 打印堆栈信息
        log.error(getStackTrace(e));
        String[] split = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
        log.info("{}",split);
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return buildResponseEntity(ApiError.error(HttpStatus.BAD_REQUEST.value(),message));
    }

    /**
     * 打印错误信息堆栈
     * @param e
     * @return
     */
    private String getStackTrace(Throwable e){
        StringWriter sw = new StringWriter();
        try(PrintWriter pw = new PrintWriter(sw)){
            e.printStackTrace(pw);
            return sw.toString();
        }
    }

    /**
     * 统一返回
     */
    protected ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
        return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
    }
}
